// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const rcbRouter = require('tcb-router')
const rp = require('request-promise')

const onelistCollection = db.collection('onelist')

const BASE_URL = 'http://v3.wufazhuce.com:8000/api'

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new rcbRouter({ event })

  app.router('readhome', async (ctx) => {
    const date = event.date
    if (date.trim() != '') {
      w = {
        'data.date': db.RegExp({
          regexp: date,
          options: 'i'
        })
      }
    }
    ctx.body = await onelistCollection.where(w)
      .get()
      .then(res => {
        return res
      })
  })

  app.router('picDetail', async (ctx) => {
    ctx.body = await rp(BASE_URL + '/hp/detail/' + parseInt(event.id))
      .then((res) => {
        return JSON.parse(res)
      })
  })


  app.router('essayDetail', async (ctx) => {
    ctx.body = await rp(BASE_URL + '/essay/' + parseInt(event.id))
      .then((res) => {
        return JSON.parse(res)
      })
  })

  app.router('serialDetail', async (ctx) => {
    ctx.body = await rp(BASE_URL + '/serialcontent/' + parseInt(event.id))
      .then((res) => {
        return JSON.parse(res)
      })
  })
  
  app.router('questionDetail', async (ctx) => {
    ctx.body = await rp(BASE_URL + '/question/' + parseInt(event.id))
      .then((res) => {
        return JSON.parse(res)
      })
  })

  app.router('movieDetail', async (ctx) => {
    ctx.body = await rp(BASE_URL + '/movie/' + parseInt(event.id) + '/story/1/0')
      .then((res) => {
        return JSON.parse(res)
      })
  })

  return app.serve()
}